let uEmailInp = document.querySelector("#usernumber");
let uEmailText = document.querySelector(".emailtext");
let passwordInp = document.querySelector("#password");
let passwordText = document.querySelector(".passtext");
let createUser = document.querySelector(".accout .createuser");
let forget = document.querySelector(".accout .forget");
let loginBtn = document.querySelector(".loginbtn");

// 创建新账号和忘记密码的跳转
createUser.onclick = function () {
  window.location.href = "../public/registe.html";
};
forget.onclick = function () {
  window.location.href = "../public/repassword.html";
};
//输入框聚焦失焦的效果
uEmailInp.addEventListener("blur", uEmailInpBlur);
uEmailInp.addEventListener("focus", uEmailInpFocus);
passwordInp.addEventListener("blur", wordInpBlur);
passwordInp.addEventListener("focus", wordInpFocus);
loginBtn.addEventListener("click", login);

function uEmailInpFocus(e) {
  let inp = e.target;
  inp.placeholder = "";
  uEmailText.classList.add("inputclick");
}

function uEmailInpBlur(e) {
  let inp = e.target;
  if (inp.value == "") {
    inp.placeholder = "邮箱";
  }
  if (inp.value == "" && inp.placeholder == "邮箱") {
    uEmailText.classList.remove("inputclick");
  }
}

function wordInpFocus(e) {
  let inp = e.target;
  inp.placeholder = "";
  passwordText.classList.add("inputclick");
}

function wordInpBlur(e) {
  let inp = e.target;
  if (inp.value == "") {
    inp.placeholder = "密码";
  }
  if (inp.value == "" && inp.placeholder == "密码") {
    passwordText.classList.remove("inputclick");
  }
}

async function login() {
  // 判断账号格式是否正确
  if (!judgeEmail()) {
    judgeRemoveTime();
  } else if (passwordInp.value.length < 8 || passwordInp.value.length > 20) {
    tipsEl.textContent = "请输入正确格式密码！";
    tipsEl.classList.add("active");
    judgeRemoveTime();
  } else {
    // 验证账号密码是否正确
    let res = await axios({
      method: "post",
      url: "http://121.37.252.168:8080/api/user/login",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${localStorage.token}`
      },
      data: {
        email: uEmailInp.value,
        password: passwordInp.value
      }
    });
    console.log(res.data);
    //  将token写进页面里
    if (res.data.code != 200) {
      tipsEl.textContent = "账号或密码错误！";
      tipsEl.classList.add("active");
      judgeRemoveTime();
    }
    //成功就跳转到记账页面
    else {
      //存储token，并且请求成功跳转主页面
      localStorage.token = res.data.data.token;
      localStorage.userinfo = JSON.stringify(res.data.data);
      window.location.href = "../public/firstPage.html";
    }
  }
}
